测试链接：https://leetcode.cn/problems/4sum/description/
#include <algorithm>
#include <vector>

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        if (nums.size() < 4)
            return {};
        sort(nums.begin(), nums.end());
        vector<vector<int>> ans;
        int n = nums.size();

        for (int i = 0; i < n;) {
            for (int j = i + 1; j < n;) {
                // if((long long)nums[i] + nums[j])
                int left = j + 1;
                int right = n - 1;
                while (left < right) {
                    while (left < right && left != j + 1 &&
                           nums[left] == nums[left - 1])
                        left++;
                    while (left < right && right != n - 1 &&
                           nums[right] == nums[right + 1])
                        right--;
                    if (left >= right)
                        break;
                    // 在相加之前将其中一个数转换为 long long 类型
                    long long sum =
                        (long long)nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == target) {
                        ans.push_back(
                            {nums[i], nums[j], nums[left], nums[right]});
                        left++;
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        right--;
                    }
                }
                j++;
                while (j < n && nums[j] == nums[j - 1])
                    j++;
            }
            i++;
            while (i < n && nums[i] == nums[i - 1])
                i++;
        }

        return ans;
    }
};